package com.atguigu.ssyx.acl.server.impl;

import com.atguigu.ssyx.acl.mapper.PermissionMapper;
import com.atguigu.ssyx.acl.server.PermissionService;
import com.atguigu.ssyx.acl.utils.PermissionHelper;
import com.atguigu.ssyx.model.acl.Permission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * ClassName: PermissionServiceImpl
 * Package: com.atguigu.ssyx.acl.server.impl
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-09-25
 * Time: 9:40
 */

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
        implements PermissionService {

    //查询所有菜单
    @Override
    public List<Permission> queryAllPermission() {
        //并不是简单的查询所有菜单 而是要显示层级关系

        //查询所以菜单
        List<Permission> allList = baseMapper.selectList(null);
        //转换格式 转换为层级关系的
        List<Permission> result = PermissionHelper.buildPermission(allList);

        return result;
    }

    //递归删除菜单
    @Override
    public void removeChildById(Long id) {
        //idList里面是所有要删除的菜单的id集合
        List<Long> idList = new ArrayList<>();
        //递归的找到要删除的菜单id
        //根据当前ID 获取当前菜单的子菜单
        //递归的去找 菜单的子菜单
        this.getAllPermissionId(id,idList);
        //把当前菜单添加进去
        idList.add(id);
        //删除的id集合 这里这是子菜单的集合
        baseMapper.deleteBatchIds(idList);
    }

    //递归找当前菜单的子菜单
    private void getAllPermissionId(Long id, List<Long> idList) {
        //根据当前菜单ID 查询当前菜单子id
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Permission::getPid,id);
        List<Permission> childList = baseMapper.selectList(wrapper);
        //递归查询 是否还有子菜单
        childList.stream().forEach(item ->{
            idList.add(item.getId());
            //递归
            this.getAllPermissionId(item.getId(),idList);
        });
    }

}
